/**
 * @(#)ApkConfigController.java 2017年03月1日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.action;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.jsbd.boss.domian.Book;
import org.jsbd.boss.domian.channel.BaseResultVo;
import org.jsbd.boss.enums.ResponseEnum;
import org.jsbd.boss.service.IBookPayLogService;
import org.jsbd.boss.service.IBookService;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.PropertiesUtil;
import org.jsbd.boss.annotation.SystemControllerLog;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ExportExcel;
import org.jsbd.boss.common.ImportExcel;
import org.jsbd.boss.common.ResponseMapUtils;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.common.ReturnJsonCode;
import org.jsbd.boss.common.redis.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/book")
public class BookController {

	public static final Logger logger = LoggerFactory.getLogger(BookController.class);
	public static final String EXCEL_NAME = "书籍列表.xlsx";

	@Autowired
	private IBookService bookService;

	@Autowired
	private RedisClient<String, Object> redisClient;

	@Autowired
	private IBookPayLogService bookPayLogService;

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(Model model) {
		return "book/list";
	}

	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(Book book) {
		if (StringUtils.isBlank(book.getName())) {
			return ResponseMapUtils.responseFail("书名不能为空");
		}

		if (book.getPayMoney() == null) {
			book.setPayMoney(new BigDecimal(0));
		}

		bookService.save(book);
		return ResponseMapUtils.responseSuccess();
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public Object update(Book book) {
		if (book.getId() == null) {
			return ResponseMapUtils.responseFail("参数缺失，请确认参数再提交");
		}
		Book obj = bookService.getById(book.getId());
		obj.setName(book.getName());
		obj.setChapter(book.getChapter());
		obj.setTotalMoney(book.getTotalMoney());
		bookService.update(obj);
		return ResponseMapUtils.responseSuccess();
	}

	@RequestMapping(value = "get")
	@ResponseBody
	@SystemControllerLog(description = "获取书信息")
	public void get(String mark, HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			Book result = bookService.getByMark(mark);
			if (result != null) {
				resultVo.setData(result.toString());
				resultVo.setMessage(ResponseEnum.SUCC.getDesc());
				resultVo.setStatus(ResponseEnum.SUCC.getStatus());
			} else {
				resultVo.setMessage(ResponseEnum.FAIL.getDesc());
				resultVo.setStatus(ResponseEnum.FAIL.getStatus());
			}
		} catch (Exception e) {
			logger.error("获取Book出错", e);
			resultVo.setMessage(ResponseEnum.ERROR.getDesc());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@RequestMapping(value = "fails")
	@ResponseBody
	@SystemControllerLog(description = "回传书籍付费失败次数")
	public void fails(Integer bookId, String mark, HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			bookService.updateFailCount(bookId,mark);
			resultVo.setMessage(ResponseEnum.SUCC.getDesc());
			resultVo.setStatus(ResponseEnum.SUCC.getStatus());
		} catch (Exception e) {
			logger.error("回传书籍付费失败次数出错", e);
			resultVo.setMessage(ResponseEnum.ERROR.getDesc());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@RequestMapping(value = "getListPage")
	@ResponseBody
	public Map<String, Object> getListPage(DataGridModel page, Book book) throws Exception {
		
		return bookService.getListPage(page, book);
	}

	@RequestMapping(value = "getTempPage")
	@ResponseBody
	public Map<String, Object> getTempPage(DataGridModel page, Book book) throws Exception {
		return bookService.getTempPage(page, book);
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void delete(Integer[] ids, HttpServletResponse response) {
		try {
			List<Integer> list = Arrays.asList(ids);
			bookService.delete(list);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	@RequestMapping(value = "/doImport", method = RequestMethod.POST)
	@SystemControllerLog(description = "excel临时表更新到表中")
	public void doImport(HttpServletResponse response, long counter, int bookGroupId) {
		try {
			bookService.tempToBook(counter, bookGroupId);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	@RequestMapping(value = "import", method = RequestMethod.POST)
	@SystemControllerLog(description = "导入excel到临时表")
	public void importExcel(@RequestParam("excelFile") MultipartFile file, HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			List<Book> list = ImportExcel.readExcel(file, Book.class);
			long count = bookService.saveToTemp(list);
			resultVo.setData(count);
			resultVo.setMessage(ResponseEnum.SUCC.getDesc());
			resultVo.setStatus(ResponseEnum.SUCC.getStatus());

		} catch (Exception e) {
			logger.error("导入excel出错", e);
			resultVo.setMessage(ResponseEnum.ERROR.getDesc());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@RequestMapping(value = "/export", method = RequestMethod.POST)
	@SystemControllerLog(description = "导出excel")
	@ResponseBody
	public void exportExcel(Book book, HttpServletResponse response) throws Exception {
		List<Book> list = bookService.getList(book);
		Integer total = list.size();

		JSONObject resultJson = new JSONObject();
		String size = PropertiesUtil.getValue("excel_max_size");
		if (total == 0) {
			resultJson.put(ReturnJsonCode.RETURN_CODE, ReturnJsonCode.MsgCodeEnum.EXCEL_EXPORT_ERROR.getCode());
			resultJson.put(ReturnJsonCode.RETURN_MSG, "操作失败！该范围内没有数据。");
			ResponseUtils.renderJson(response, resultJson.toString());
			return;
		}
		if (total > Integer.parseInt(size)) {
			resultJson.put(ReturnJsonCode.RETURN_CODE, ReturnJsonCode.MsgCodeEnum.EXCEL_EXPORT_ERROR.getCode());
			resultJson.put(ReturnJsonCode.RETURN_MSG, "操作失败！查询数据超过excel可导出上限。");
			ResponseUtils.renderJson(response, resultJson.toString());
			return;
		}

		response.setContentType("octets/stream");
		response.addHeader("Content-Disposition",
				"attachment;filename=" + new String(EXCEL_NAME.getBytes("gb2312"), "iso8859-1"));

		ExportExcel<Book> excel = new ExportExcel<Book>();
		String[] headers = { "书名", "章节 ", "总金额", "已支付金额", "总失败次数"};
		OutputStream out = response.getOutputStream();

		excel.exportExcel(EXCEL_NAME, headers, list, out, "yyyy-MM-dd");

		out.close();
	}

	@RequestMapping(value = "revert", method = RequestMethod.POST)
	@ResponseBody
	public void revert(HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			int counter = bookService.revertAllBookPayMoney();
			resultVo.setData(counter);
			resultVo.setMessage(ResponseEnum.SUCC.getDesc());
			resultVo.setStatus(ResponseEnum.SUCC.getStatus());

		} catch (Exception e) {
			logger.error("书籍中，已支付金额清零出错", e);
			resultVo.setMessage(ResponseEnum.ERROR.getDesc());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@RequestMapping(value = "revert/time/get")
	@ResponseBody
	public void revertTime(HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			Object obj = redisClient.get(CacheKey.BOOK_REVERT_TIME);
			resultVo.setData(obj == null ? null : obj.toString());
			resultVo.setMessage(ResponseEnum.SUCC.getDesc());
			resultVo.setStatus(ResponseEnum.SUCC.getStatus());

		} catch (Exception e) {
			logger.error("获取恢复执行时间出错", e);
			resultVo.setMessage(ResponseEnum.ERROR.getDesc());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@RequestMapping(value = "revert/time/set", method = RequestMethod.POST)
	@ResponseBody
	public void revertTimeSet(String time, HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			redisClient.put(CacheKey.BOOK_REVERT_TIME, (Object) time, -1);

			Object obj = redisClient.get(CacheKey.BOOK_REVERT_TIME);
			resultVo.setData(obj == null ? null : obj.toString());
			resultVo.setMessage(ResponseEnum.SUCC.getDesc());
			resultVo.setStatus(ResponseEnum.SUCC.getStatus());

		} catch (Exception e) {
			logger.error("设置恢复执行时间出错", e);
			resultVo.setMessage(ResponseEnum.ERROR.getDesc());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}
}
